package user

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"net/http"
)

var db *gorm.DB

func AddUser(c *gin.Context) {
	dsn := "root:@tcp(127.0.0.1:3306)/web2?charset=utf8mb4&parseTime=True&loc=Local"
	// 连接数据库
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败:", err)
		return
	}
	// 自动迁移模型（创建表）
	err1 := db.AutoMigrate(&User{})
	if err1 != nil {
		return
	}

	db.Create(&User{UserName: "bgbiao", Age: 18, Email: "bgbiao@bgbiao.top"})
	db.Create(&User{UserName: "xxb", Age: 18, Email: "xxb@bgbiao.top"})

	c.JSON(http.StatusOK, gin.H{
		"message": "add user success",
	})
}

func FindUserByUserName(username string) User {
	dsn := "root:@tcp(127.0.0.1:3306)/web2?charset=utf8mb4&parseTime=True&loc=Local"
	// 连接数据库
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败:", err)
	}

	// 查询用户
	var user User
	result := db.Where("user_name = ?", username).First(&user)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			fmt.Println("User not found")
		} else {
			fmt.Println("Error:", result.Error)
		}
	} else {
		fmt.Println("User found:", user)
	}

	return user
}

func Register(c *gin.Context) {

	password := c.Query("password")
	username := c.Query("username")
	phoneNumber := c.Query("phoneNumber")

	dsn := "root:123456@tcp(127.0.0.1:3306)/web2?charset=utf8&parseTime=True&loc=Local"
	// 连接数据库
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败:", err)
		return
	}
	// 自动迁移模型（创建表）
	err1 := db.AutoMigrate(&User{})
	if err1 != nil {
		return
	}

	db.Create(&User{UserName: username, Age: 18, Email: "bgbiao@bgbiao.top", Password: password, PhoneNumber: phoneNumber})

	c.JSON(http.StatusOK, gin.H{
		"message": "register user success",
	})

}

func Login(c *gin.Context) {

	var command LoginCommand
	err := c.BindJSON(&command)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"error": "get parameters error !!!",
		})
		return
	}

	username := command.Username
	password := command.Password

	user := FindUserByUserName(username)

	if password == user.Password {
		c.JSON(http.StatusOK, gin.H{
			"success": "login success !!!",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"error": "login error !!!",
		})
	}

}
